<template>
    <el-main style="background:#f7f8fa;">
      <div style="display:flex;justify-content:flex-end;align-items:center;margin-bottom:8px;gap:16px;">
        <el-button v-if="!props.isGuestMode" type="primary" size="small" @click="onRefreshStats">刷新</el-button>
      </div>
      <el-row :gutter="24" style="margin-bottom:24px;">
        <el-col :span="5">
          <el-card class="dashboard-card">
            <div class="card-title">设备总数</div>
            <div class="card-value" style="cursor:pointer;" @click="goDeviceList">{{ totalDisplay }}</div>
          </el-card>
        </el-col>
        <el-col :span="5">
          <el-card class="dashboard-card">
            <div class="card-title">维修记录数</div>
            <div class="card-value">{{ stats.repairCount }}</div>
          </el-card>
        </el-col>
        <el-col :span="5">
          <el-card class="dashboard-card">
            <div class="card-title">备件库存数</div>
            <div class="card-value">{{ stats.sparePartCount }}</div>
          </el-card>
        </el-col>
        <el-col :span="5">
          <el-card class="dashboard-card">
            <div class="card-title">出厂报告数</div>
            <div class="card-value">{{ stats.reportCount }}</div>
          </el-card>
        </el-col>
        <el-col :span="4">
          <el-card class="dashboard-card">
            <div class="card-title">文档总数</div>
            <div class="card-value">{{ stats.documentCount }}</div>
          </el-card>
        </el-col>
      </el-row>
      <el-row :gutter="24" style="margin-bottom:24px;">
        <el-col :span="24">
          <!-- 删除上方单独卡片区的近期异常设备 -->
        </el-col>
      </el-row>
      <el-row :gutter="24">
        <el-col :span="12">
          <el-card class="dashboard-table-card">
            <div class="table-title">最近校正的设备</div>
            <el-table :data="recentCalibrations.slice(0, 10)" border>
              <el-table-column prop="code" label="设备编号" width="120" />
              <el-table-column prop="name" label="设备名称" width="120" />
              <el-table-column prop="calibrationTime" label="校正时间" width="140" />
              <el-table-column prop="operator" label="校正人" width="100" />
              <el-table-column prop="result" label="校正结果" width="100" />
            </el-table>
            <div v-if="recentCalibrations.length > 10" style="text-align:right;margin-top:8px;">
              <el-button size="small" type="primary" @click="onShowCalibrationDialog">查看更多</el-button>
            </div>
          </el-card>
        </el-col>
        <el-col :span="12">
          <el-card class="dashboard-table-card">
            <div class="table-title">最新报修记录</div>
            <el-table :data="repairRecords.slice(0, 10)" border>
              <el-table-column prop="repCode" label="报修单号" width="120" />
              <el-table-column prop="name" label="设备名称" width="120" />
              <el-table-column prop="reporter" label="报修人" width="100" />
              <el-table-column prop="reportTime" label="报修时间" width="140" />
              <el-table-column prop="desc" label="故障描述" width="180" />
              <el-table-column prop="status" label="处理状态" width="100" />
            </el-table>
            <div v-if="repairRecords.length > 10" style="text-align:right;margin-top:8px;">
              <el-button size="small" type="primary" @click="onShowRepairDialog">查看更多</el-button>
            </div>
          </el-card>
        </el-col>
      </el-row>
      <!-- 校正记录弹窗 -->
      <el-dialog v-model="showCalibrationDialog" title="全部校正记录" width="800px">
        <el-table :data="recentCalibrations" border>
          <el-table-column prop="code" label="设备编号" width="120" />
          <el-table-column prop="name" label="设备名称" width="120" />
          <el-table-column prop="calibrationTime" label="校正时间" width="140" />
          <el-table-column prop="operator" label="校正人" width="100" />
          <el-table-column prop="result" label="校正结果" width="100" />
        </el-table>
      </el-dialog>
      <!-- 报修记录弹窗 -->
      <el-dialog v-model="showRepairDialog" title="全部报修记录" width="800px">
        <el-table :data="repairRecords" border>
          <el-table-column prop="repCode" label="报修单号" width="120" />
          <el-table-column prop="name" label="设备名称" width="120" />
          <el-table-column prop="reporter" label="报修人" width="100" />
          <el-table-column prop="reportTime" label="报修时间" width="140" />
          <el-table-column prop="desc" label="故障描述" width="180" />
          <el-table-column prop="status" label="处理状态" width="100" />
        </el-table>
      </el-dialog>
    </el-main>
  </template>
  
  <script setup>
import { ref, onMounted, computed, onUnmounted, nextTick, watch } from 'vue'
import AV from '../leancloud'
import { use } from 'echarts/core'
import VChart from 'vue-echarts'
import { PieChart, GaugeChart, BarChart } from 'echarts/charts'
import { TooltipComponent, LegendComponent, TitleComponent } from 'echarts/components'
import { CanvasRenderer } from 'echarts/renderers'
import { defineProps } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'

use([PieChart, GaugeChart, BarChart, TooltipComponent, LegendComponent, TitleComponent, CanvasRenderer])

// 定义props
const props = defineProps({
  isGuestMode: Boolean
})
  
  const stats = ref({
    total: 0, // 设备总数
    calibrationRate: 0,
    calibrationShould: 0,
    calibrationDone: 0,
    statusCount: { '正常运行': 0, '异常': 0, '维修中': 0, '备用': 0, '报废': 0 },
    repairCount: 0, // 维修记录数
    sparePartCount: 0, // 备件库存数
    reportCount: 0, // 出厂报告总数
    documentCount: 0 // 文档总数
  })
  const abnormalDevices = ref([])
  const repairRecords = ref([])
  const showAbnormalDialog = ref(false)
  const showRepairDialog = ref(false)
  const recentCalibrations = ref([])
  const showCalibrationDialog = ref(false)

  async function loadStats() {
    try {
      // 设备总数和状态分布
      const query = new AV.Query('Device')
      query.limit(1000)
      const results = await query.find()
      stats.value.total = results.length
      const count = { '正常运行': 0, '异常': 0, '维修中': 0, '备用': 0, '报废': 0 }
      // 统计有校正方案且状态为正常或正常运行的设备
      const calibrationDevices = results.filter(d => d.get('calibrationPlan') === '每班校正' && ['正常运行', '正常'].includes(d.get('status')))
      // 计算当前班次
      const now = new Date();
      const hour = now.getHours();
      let shift = '';
      if (hour < 8) shift = '0-8';
      else if (hour < 16) shift = '8-16';
      else shift = '16-24';
      // 本月天数
      const monthStart = new Date(now.getFullYear(), now.getMonth(), 1)
      const monthEnd = new Date(now.getFullYear(), now.getMonth() + 1, 0)
      const daysInMonth = monthEnd.getDate()
      // 只统计当前班次的应校正次数
      stats.value.calibrationShould = calibrationDevices.length
      // 本月校正记录
      const actionQuery = new AV.Query('DeviceActionRecord')
      actionQuery.greaterThanOrEqualTo('date', monthStart)
      actionQuery.lessThan('date', new Date(now.getFullYear(), now.getMonth() + 1, 1))
      actionQuery.equalTo('type', '校正')
      actionQuery.limit(1000)
      const actions = await actionQuery.find()
      // 统计每台设备每天每班次是否有校正
      const doneSet = new Set()
      actions.forEach(r => {
        const devId = r.get('device')?.id
        if (!devId) return
        // 只统计有校正方案的设备
        if (!calibrationDevices.find(d => d.id === devId)) return
        const date = new Date(r.get('date'))
        const day = date.toISOString().slice(0, 10)
        doneSet.add(`${devId}_${day}_${shift}`)
      })
      stats.value.calibrationDone = doneSet.size
      stats.value.calibrationRate = stats.value.calibrationShould
        ? Math.round((doneSet.size / stats.value.calibrationShould) * 100)
        : 0
      results.forEach(d => {
        count[d.get('status')] = (count[d.get('status')] || 0) + 1
      })
      stats.value.statusCount = count
    
      // 串行统计其它业务模块
      stats.value.repairCount = await new AV.Query('RepairRecord').count()
      stats.value.sparePartCount = await new AV.Query('SparePart').count()
      stats.value.reportCount = await new AV.Query('FactoryReport').count()
      stats.value.documentCount = await new AV.Query('Document').count()
    
      // 近期异常设备（近7天有异常的设备）
      const weekAgo = new Date(Date.now() - 7 * 24 * 3600 * 1000)
      const abnormalQuery = new AV.Query('DeviceRecord')
      abnormalQuery.greaterThanOrEqualTo('date', weekAgo)
      abnormalQuery.equalTo('type', '检查')
      abnormalQuery.equalTo('status', '异常')
      abnormalQuery.include('device')
      abnormalQuery.descending('date')
      abnormalQuery.limit(10)
      const abnormalList = await abnormalQuery.find()
      abnormalDevices.value = abnormalList.map(r => ({
        code: r.get('device')?.get('code') || '',
        name: r.get('device')?.get('name') || '',
        checkTime: r.get('date') ? new Date(r.get('date')).toLocaleDateString() : '',
        reason: r.get('reason') || '',
        status: r.get('status') || ''
      }))
    
      // 最新报修记录
      const repairListQuery = new AV.Query('RepairRecord')
      repairListQuery.descending('createdAt')
      repairListQuery.limit(10)
      repairListQuery.include('device') // 关键
      const repairList = await repairListQuery.find()
      repairRecords.value = repairList.map(r => ({
        repCode: r.get('repCode') || '',
        name: r.get('device')?.get('name') || '',
        reporter: r.get('reporter') || '',
        reportTime: r.get('reportTime') ? new Date(r.get('reportTime')).toLocaleString() : '',
        desc: r.get('desc') || '',
        status: r.get('status') || ''
      }))

      // 获取最近10条校正记录
      const calibrationQuery = new AV.Query('DeviceActionRecord')
      calibrationQuery.equalTo('type', '校正')
      calibrationQuery.descending('date')
      calibrationQuery.limit(10)
      calibrationQuery.include('device')
      const calibrationList = await calibrationQuery.find()
      console.log('校正记录 device 字段：', calibrationList.map(r => r.get('device')))
      console.log('校正记录原始数据：', calibrationList)
      recentCalibrations.value = calibrationList.map(r => {
        const device = r.get('device');
        return {
          code: device?.get ? device.get('code') : (device?.code || device || ''),
          name: device?.get ? device.get('name') : (device?.name || ''),
          calibrationTime: r.get('date') ? new Date(r.get('date')).toLocaleString() : '',
          operator: r.get('operator') || '',
          result: r.get('result') || ''
        }
      })
    } catch (e) {
      if (e.code === 429 || (e.message && e.message.includes('429'))) {
        ElMessage.error('请求过于频繁，请稍后再试');
      } else {
        ElMessage.error('统计数据加载失败: ' + e.message);
      }
    }
  }

  function refreshStats() {
    loadStats()
  }

  let timer = null
  let legendScrollTimer = null
  let legendScrollIndex = 0

  function startLegendAutoScroll() {
    nextTick(() => {
      const chart = document.querySelector('.dashboard-card .v-chart')?.__vchart__?.getEchartsInstance?.()
      if (!chart) return
      legendScrollTimer = setInterval(() => {
        const option = chart.getOption()
        const legendData = option.legend[0].data
        legendScrollIndex = (legendScrollIndex + 1) % legendData.length
        chart.dispatchAction({
          type: 'legendScroll',
          scrollDataIndex: legendScrollIndex
        })
      }, 2000)
    })
  }

  function stopLegendAutoScroll() {
    if (legendScrollTimer) clearInterval(legendScrollTimer)
    legendScrollTimer = null
  }

  onMounted(() => {
    loadStats()
    timer = setInterval(loadStats, 180000) // 3分钟刷新一次
    startLegendAutoScroll()
  })
  onUnmounted(() => {
    if (timer) clearInterval(timer)
    stopLegendAutoScroll()
  })
  
  // 校正完成率环形图
  const calibrationRateOption = computed(() => ({
    series: [
      {
        type: 'gauge',
        startAngle: 90,
        endAngle: -270,
        progress: { show: true, width: 20 },
        axisLine: { lineStyle: { width: 20 } },
        pointer: { show: false },
        axisTick: { show: false },
        splitLine: { show: false },
        axisLabel: { show: false },
        data: [{ value: stats.value.calibrationRate }],
        detail: {
          valueAnimation: true,
          fontSize: 28,
          color: '#409EFF',
          formatter: '{value}%'
        },
        title: { show: false }
      }
    ]
  }))
  
  // 设备状态分布柱状图
  const statusNames = ['正常运行', '异常', '维修中', '备用', '报废']
  const statusColors = ['#5470c6', '#ee6666', '#fac858', '#91cc75', '#73c0de'] // 可根据实际配色调整
  const statusBarOption = computed(() => ({
    tooltip: { trigger: 'axis' },
    grid: { left: 20, right: 20, bottom: 40, top: 40, containLabel: true },
    xAxis: {
      type: 'category',
      data: statusNames,
      axisLabel: { fontSize: 14 }
    },
    yAxis: {
      type: 'value',
      minInterval: 1,
      axisLabel: { fontSize: 14 }
    },
    series: [
      {
        data: statusNames.map((name, i) => ({
          value: stats.value.statusCount[name],
          itemStyle: { color: statusColors[i % statusColors.length] }
        })),
        type: 'bar',
        barWidth: 32,
        label: {
          show: true,
          position: 'top',
          fontSize: 14
        }
      }
    ]
  }))

  // 数字动画钩子
  function useCountUp(target, duration = 800) {
    const display = ref(0)
    let timer = null
    watch(target, (val, oldVal) => {
      if (timer) clearInterval(timer)
      const start = Number(oldVal) || 0
      const end = Number(val) || 0
      const step = Math.ceil((end - start) / (duration / 16))
      let current = start
      timer = setInterval(() => {
        current += step
        if ((step > 0 && current >= end) || (step < 0 && current <= end)) {
          display.value = end
          clearInterval(timer)
          timer = null
        } else {
          display.value = current
        }
      }, 16)
    }, { immediate: true })
    return display
  }

  const totalDisplay = useCountUp(computed(() => stats.value.total))
  const calibrationRateDisplay = useCountUp(computed(() => stats.value.calibrationRate))

  const router = useRouter()

  function requireLogin(action) {
    if (props.isGuestMode) {
      ElMessage.warning('请先登录后操作')
      router.push('/login')
      return
    }
    action()
  }
  // 包装操作
  function onRefreshStats() { requireLogin(refreshStats) }
  function onShowAbnormalDialog() { requireLogin(() => showAbnormalDialog.value = true) }
  function onShowRepairDialog() { requireLogin(() => showRepairDialog.value = true) }
  function onShowCalibrationDialog() { requireLogin(() => showCalibrationDialog.value = true) }

  function goDeviceList() {
    router.push('/device-list')
  }
  </script>
  
  <style scoped>
  .dashboard-card {
    height: auto;
    min-height: 260px;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    box-shadow: 0 2px 12px 0 rgba(0,0,0,0.04);
    border-radius: 12px;
    background: #fff;
    position: relative;
    padding: 24px 16px 32px 16px;
  }
  .card-title {
    font-size: 20px;
    font-weight: bold;
    color: #333;
    margin-bottom: 12px;
    text-align: center;
  }
  .card-value {
    font-size: 48px;
    font-weight: bold;
    color: #409EFF;
    margin-top: 16px;
    text-align: center;
  }
  .dashboard-table-card {
    border-radius: 12px;
    box-shadow: 0 2px 12px 0 rgba(0,0,0,0.04);
    background: #fff;
    margin-bottom: 24px;
  }
  .table-title {
    font-size: 18px;
    font-weight: bold;
    color: #333;
    margin-bottom: 12px;
  }
  .custom-legend-scroll {
    width: 220px;
    overflow: hidden;
    height: 28px;
    margin: 0 auto 0 auto;
    position: absolute;
    left: 0;
    right: 0;
    bottom: 24px;
    z-index: 2;
    background: #fff;
    border-radius: 14px;
    box-shadow: 0 1px 4px 0 rgba(0,0,0,0.04);
    display: flex;
    align-items: center;
    justify-content: center;
  }
  .legend-track {
    display: flex;
    width: max-content;
    animation: legend-scroll 18s linear infinite;
  }
  .legend-item {
    display: flex;
    align-items: center;
    font-size: 14px;
    margin-right: 32px;
    white-space: nowrap;
    border-radius: 12px;
    border: 1px solid;
    padding: 2px 12px 2px 6px;
    background: #fff;
    box-shadow: 0 1px 4px 0 rgba(0,0,0,0.04);
  }
  .legend-dot {
    display: inline-block;
    width: 12px;
    height: 12px;
    border-radius: 50%;
    margin-right: 6px;
  }
  @keyframes legend-scroll {
    0% { transform: translateX(0); }
    100% { transform: translateX(-50%); }
  }
  .status-list {
    list-style: none;
    padding: 0;
    margin: 0;
    display: flex;
    flex-direction: column;
    gap: 8px;
  }
  .status-list li {
    font-size: 16px;
    display: flex;
    align-items: center;
  }
  .legend-dot {
    display: inline-block;
    width: 14px;
    height: 14px;
    border-radius: 50%;
    margin-right: 8px;
  }
/* 统一按钮样式 */
.dashboard-header .el-button {
  font-weight: 600;
  font-size: 14px;
  padding: 8px 16px;
  border-radius: 6px;
  gap: 6px;
  height: 36px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;
}

.dashboard-header .el-button[type="primary"] {
  background: linear-gradient(135deg, #409eff 0%, #337ecc 100%);
  border: 1px solid #409eff;
  color: white;
}

.dashboard-header .el-button[type="primary"]:hover {
  background: linear-gradient(135deg, #337ecc 0%, #2d5aa0 100%);
  border-color: #337ecc;
  transform: translateY(-1px);
  box-shadow: 0 4px 8px rgba(64, 158, 255, 0.3);
}

/* 卡片中的按钮样式 */
.dashboard-card .el-button,
.dashboard-table-card .el-button {
  font-weight: 600;
  font-size: 12px;
  padding: 6px 12px;
  border-radius: 4px;
  gap: 4px;
  height: 30px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;
}

.dashboard-card .el-button[type="primary"],
.dashboard-table-card .el-button[type="primary"] {
  background: linear-gradient(135deg, #409eff 0%, #337ecc 100%);
  border: 1px solid #409eff;
  color: white;
}

.dashboard-card .el-button[type="primary"]:hover,
.dashboard-table-card .el-button[type="primary"]:hover {
  background: linear-gradient(135deg, #337ecc 0%, #2d5aa0 100%);
  border-color: #337ecc;
  transform: translateY(-1px);
  box-shadow: 0 3px 6px rgba(64, 158, 255, 0.3);
}

/* 确保按钮内容居中 */
.el-button .el-button__content {
  display: flex;
  justify-content: center;
  align-items: center;
}

@media (max-width: 700px) {
    .dashboard-card, .dashboard-table-card {
      min-width: unset;
      width: 100% !important;
      margin-bottom: 16px;
      padding: 12px 6px 18px 6px;
    }
    .card-title, .table-title {
      font-size: 18px;
      margin-bottom: 8px;
    }
    .card-value {
      font-size: 32px;
      margin-top: 8px;
    }
    .el-row {
      flex-direction: column !important;
      gap: 0;
    }
    .el-col {
      width: 100% !important;
      max-width: 100% !important;
      flex: 1 1 100%;
    }
    .el-table {
      font-size: 13px;
      min-width: 600px;
      overflow-x: auto;
      display: block;
    }
    .el-table__body-wrapper {
      overflow-x: auto !important;
    }
    .el-button, .el-input, .el-select {
      font-size: 16px !important;
      min-height: 38px !important;
    }
    .el-pagination {
      font-size: 15px;
      padding: 8px 0;
    }
    .dashboard-card, .dashboard-table-card {
      box-shadow: 0 1px 4px 0 rgba(0,0,0,0.08);
    }
  }
  </style>
  